package com.bw.mine.model.service

import com.baweigame.xmpplibrary.XmppManager
import com.bw.mine.intent.RegisterIntent
import com.bw.mine.model.api.UserCenterApi
import com.bw.mine.state.RegisterState
import com.bw.mvicore.model.BaseModel
import com.bw.net.RetrofitUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.consumeAsFlow

/**
 * @author:created by hahajing
 * 时间：2024/5/6 0006
 * 企鹅号:444511958
 * 描述:
 */
class RegisterModel:BaseModel<RegisterIntent>() {
    private val api: UserCenterApi by lazy {
        RetrofitUtils.create(UserCenterApi::class.java)
    }
    override fun handleIntent() {
        generateViewModelScope {
            intents.consumeAsFlow().collect{
                when(it){
                    is RegisterIntent.FinalRegisterIntent->{
                        register(it)
                    }
                }
            }
        }
    }

    private val _state: MutableStateFlow<RegisterState> = MutableStateFlow(RegisterState.RegisterDefaultState)
    val state: MutableStateFlow<RegisterState>
        get() = _state

    private suspend fun register(it: RegisterIntent.FinalRegisterIntent) {
        val result =  api.register(it.username,it.password)

        //XMPP服务器注册
        XmppManager.getInstance().xmppUserManager.createAccount(it.username,it.password)
        if (result.code==0){
            _state.value = RegisterState.RegisterSuccessState(result.data)
        }else{
            _state.value = RegisterState.RegisterFailedState(IllegalStateException("注册失败，info:${result.msg}"))
        }
    }
}